let layer = layui.layer;
let form = layui.form
$(function () {
  initArticleClassifies()
  let addindex = null
  var editIndex = null
  $('#addArticle-button').click(function () {
    addindex = layer.open({
      type: 1,
      area: ['500px', '250px'],
      title: '添加文章分类',
      content: $('#layer-open-content').html()
    })
  })

  $('body').on('submit', '#form-add', function (e) {
    e.preventDefault()
    $.ajax({
      type: "post",
      url: "/my/article/addcates",
      data: $(this).serialize(),
      success: function (res) {
        console.log(res)
        if (res.status == 0) {
          initArticleClassifies()
        } else {
          return layer.msg('添加失败')
        }
        layer.close(addindex)
      }
    })
  })

  $('tbody').on('click', 'button', function () {
    let dataId = $(this).parent().attr('data-id')
    if ($(this).attr('id') == 'articleEditButton') {
      editIndex = layer.open({
        type: 1,
        area: ['500px', '250px'],
        title: '修改文章分类',
        content: $('#layer-edit-content').html()
      })
      $.ajax({
        type: "get",
        url: `/my/article/cates/${dataId}`,
        success: function (res) {
          console.log(res);
          if (res.status == 0) {
            form.val('form-edit', res.data)
          }
        }
      })
    }

    if ($(this).attr('id') == 'articleDeleteButton') {
      layer.confirm('确认删除?', {
        icon: 3,
        title: '提示'
      }, function (index) {
        // 目前第二种传参方式 只传参数值 参数名由后端自己定义
        $.ajax({
          type: "get",
          url: `/my/article/deletecate/${dataId}`,
          success: function (res) {
            if (res.status == 0) {
              layer.msg(res.message, {
                time: 500
              }, function (index) {
                initArticleClassifies()
              })
            } else {
              return layer.msg(res.message)
            }
          }
        })
      });
    }
  })
  $('body').on('submit', '#form-edit', function (e) {
    e.preventDefault()
    $.ajax({
      type: "post",
      url: "/my/article/updatecate",
      data: $(this).serialize(),
      success: function (res) {
        console.log(res);
        if (res.status == 0) {
          layer.close(editIndex)
          initArticleClassifies()
        } else {
          return layer.msg(res.message)
        }
      }
    })
  })
})

// 获取文章分类
function initArticleClassifies() {
  $.ajax({
    type: "get",
    url: "/my/article/cates",
    success: function (res) {
      if (res.status == 0) {
        let str = template('article-list-msg', res)
        $('tbody').empty().html(str)
      } else {
        return layer.msg(res.message)
      }

    }
  })
}
